/**
 * 
 */
package com.ao.andou.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.ao.andou.R;
import com.ao.andou.common.OauthHelper;

/**
 * Login activity
 * @author pentiumao
 *
 */
public class LoginActivity extends Activity {

    private final static String TAG = "LoginActivity";
    
    private final static int LOGIN = 0;
    
    /* (non-Javadoc)
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);
        
        Button login = (Button) findViewById(R.id.btn_login);
        Button logout = (Button) findViewById(R.id.btn_logout);
        
        Intent intent = getIntent();
        Uri callback = intent.getData();
        if (intent != null && callback != null) {
            Log.d(TAG, "callback");
            String oauthToken = callback.getQueryParameter("oauth_token");
            try {
                String accessToken = OauthHelper.changeAcessToken(oauthToken);
                Log.d(TAG, "accessToken " + accessToken);
                OauthHelper.saveAccessToken(getApplicationContext(), accessToken);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Intent i = new Intent(getApplicationContext(), MainActivity.class);
            i.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            startActivity(i);
            finish();
        }
        
        login.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                try {
                    OauthHelper.getRequestToken();
                    Intent web = OauthHelper.getAuthorization();
                    startActivityForResult(web, LOGIN);
                } catch (Exception e) {
                    Log.e(TAG, "oauth error", e);
                    LoginActivity.this.finish();
                }
            }

        });
        
        logout.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                LoginActivity.this.finish();
            }
        });
    }
}
